package org.example.web;

import org.example.config.RabbitMqConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

@SpringBootApplication(scanBasePackageClasses = {MyWebApplication.class, RabbitMqConfiguration.class})
public class MyWebApplication extends SpringBootServletInitializer implements EnvironmentAware {
    private static final Logger logger = LoggerFactory.getLogger(MyWebApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(MyWebApplication.class, args);
        doSomething();
        log("main() is executing");
    }

    @Override
    public void setEnvironment(Environment environment) {
        log("active profiles are " + environment.getActiveProfiles());
        log("setEnvironment() is executing");
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.setInitParameter("spring.profiles.active", "war-mode");
        super.onStartup(servletContext);
        log("onStartup() is executing");
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        // !important 不要忘记了这个，这时不再运行main方法
        doSomething();
        log("configure() is executing");
        return builder.sources(new Class[]{MyWebApplication.class});
    }

    private static void log(String msg) {
        logger.info(msg);
        System.out.println(">>>>>>>>>>" + msg);
    }

    static void doSomething() {
        // 额外做一些事情
    }
}